<?php
// +---------------------------------------------------------------------+
// | OneBase    | [ WE CAN DO IT JUST THINK ]                            |
// +---------------------------------------------------------------------+
// | Licensed   | http://www.apache.org/licenses/LICENSE-2.0 )           |
// +---------------------------------------------------------------------+
// | Author     | Bigotry <3162875@qq.com>                               |
// +---------------------------------------------------------------------+
// | Repository | https://gitee.com/Bigotry/OneBase                      |
// +---------------------------------------------------------------------+

namespace app\admin\logic;

use app\common\model\BetsLog;
use app\common\model\ForumBbs;
use app\common\model\ForumBbsComment;
use app\common\model\GamblerKing;
use app\common\model\GamblerKingAction;
use app\common\model\GamblerKingInvestmentUser;
use app\common\model\GamblerKingInvestmentUserLog;
use app\common\model\KingCategory;
use app\common\model\SbNotice;
use app\common\model\UserAccount;
use app\common\model\UserAccountLog;
use app\common\model\UserKingInvestment;
use app\common\model\UserSms;
use think\Db;

/**
 * 交易员逻辑
 */
class King extends AdminBase
{



    /**
     * 获取交易员列表
     */
    public function getKingList($data = [], $field = 'a.*', $order = '')
    {

        $this->modelGamblerKing->alias('a');
        if(!empty($data['tags'])){
            $where['a.tags']=['like','%,'.$data['tags'].',%'];
        }
        if (!empty($data['date']) && !empty($data['date1'])) {
            $where['a.create_time'] = ['between', [strtotime($data['date'] . ' 00:00:00'), strtotime($data['date1'] . ' 23:59:59')]];
        }
        if(!empty($data['username'])){
            $where['m.username']=['like','%'.$data['username'].'%'];
        }
        if(!empty($data['is_apply'])){
            $where['a.state']=['neq',2];
        }
        if(!empty($data['state'])){
            $where['a.state']=$data['state'];
        }
        if(!empty($data['search_data'])){
            $where['a.name | m.id|m.mobile|m.username']=$data['search_data'];
        }
        $where['a.' . DATA_STATUS_NAME] = ['neq', DATA_DELETE];
        $count=$this->modelGamblerKing->alias('a')->join('__MEMBER__ m','a.user_id=m.id')->where($where)->count();


        $list=$this->modelGamblerKing->alias('a')->join('__MEMBER__ m','a.user_id=m.id')->field($field)->where($where)->paginate(50);

        return ['list'=>$list,'count'=>$count];
    }



    /**
     * 获取交易员列表搜索条件
     */
    public function getWhere($data = [])
    {

        $where = [];

        !empty($data['search_data']) && $where['a.name|a.describe'] = ['like', '%'.$data['search_data'].'%'];

        return $where;
    }

    /**
     * 交易员信息编辑
     */
    public function KingEdit($data = [])
    {

        $validate_result = $this->validateKing->scene('edit')->check($data);

        if (!$validate_result) {

            return [RESULT_ERROR, $this->validateKing->getError()];
        }

        $url = url('KingList');

        // empty($data['id']) && $data['member_id'] = MEMBER_ID;

//      $data['content'] = htmlspecialchars_decode($data['content']);
        preg_match_all('/<img.*?src="(.*?)".*?\/?>/i', $data['content'], $out, PREG_PATTERN_ORDER);      //正则匹配img标签的src属性，返回二维数组
        if (!empty($out[1])) {
            foreach ($out[1] as $v) {
                if(!preg_match('/http/',$v)){
                    $url1 = DMOAIN_URL.$v;
                    $data['content'] = str_replace($v, $url1, $data['content']);   //替换相对路径为绝对路径
                }
            }
        }
        $tags_array=explode(',',$data['tags']);
        $cate_ids=KingCategory::where(['id'=>['in',$tags_array]])->group('parent_id')->column('parent_id');
        $data['cates']=','.implode(',',$cate_ids).',';
        $result = $this->modelGamblerKing->setInfo($data);

        $handle_text = empty($data['id']) ? '新增' : '编辑';

        $result && action_log($handle_text, '交易员' . $handle_text . '，name：' . $data['name']);

        return $result ? [RESULT_SUCCESS, '交易员操作成功', $url] : [RESULT_ERROR, $this->modelGamblerKing->getError()];
    }

    /**
     * 获取交易员信息
     */
    public function getKingInfo($where = [], $field = 'a.*,m.nickname,c.name as category_name')
    {

        $this->modelGamblerKing->alias('a');


        $where['a.' . DATA_STATUS_NAME] = ['neq', DATA_DELETE];


        return $this->modelGamblerKing->getInfo($where, $field);
    }

 
    /**
     * 交易员删除
     */
    public function KingDel($where = [])
    {

        $result = $this->modelGamblerKing->deleteInfo($where);

        $result && action_log('删除', '交易员删除，where：' . http_build_query($where));

        return $result ? [RESULT_SUCCESS, '交易员删除成功'] : [RESULT_ERROR, $this->modelGamblerKing->getError()];
    }


    /**
     *
     */
    public function update_info($where = [])
    {

        //dd($where);
        $stat=$where['state'];
        $info=$this->modelGamblerKing->getInfo(['id'=>$where['id']]);
        if($where['state']==3){
            $where['is_investment']=0;
            $where['state']=3;
            if($info['is_edit']==1){
                $json=json_decode($info['prev_info'],true);
                $where['name']=$json['name'];
                $where['describe']=$json['describe'];
                $where['content']=$json['content'];
                $where['tags']=$json['tags'];
                $where['is_edit']=0;
                $where['cates']=$json['cates'];
                //发送系统通知
                user_notice($info->user_id,'您的交易员信息修改未通过审核');
            }
        }else{
            $where['is_investment']=1;
        }
        $result = $this->modelGamblerKing->setInfo($where);

        if($stat==2){

            $list= $this->modelGamblerKingInvestment->getList(['status'=>1],'',false);
            $arrs=$update_ids=[];
            foreach ($list as $k=>$v){
                if($k<3){
                    $round=$this->modelGamblerKingInvestmentUser->where(['investment_id'=>$v['id'],'king_id'=>$info['id']])->order('id desc')->value('round')+0;
                    $arr=[
                        'investment_id'=>$v['id'],
                        'king_id'=>$where['id'],
                        'user_id'=>$info['user_id'],
                        'state'=>1,
                        'round'=>$round+1,
                        'create_time'=>time(),
                        'trade_no'=>'KI'.date('Ymd').substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8).rand(1000,9999),
                        'price'=>$v['price'],
                        'max_money'=>$v['superior_money'],
                        // 'start_time'=>$v['start_time_int'],
                        // 'expire_time'=>$v['start_game_int'],
                        // 'start_game_end_int'=>$v['start_game_end_int'],
                        // 'settlement_time'=>$v['end_timev_int'],
                        'start_time'=>strtotime(date('Y-m-d').' '.$v['start_time']),
                        'expire_time'=>strtotime(date('Y-m-d').' '.$v['start_time'])+$v['cycle']*86400,
                        'start_game_end_int'=>strtotime(date('Y-m-d').' '.$v['start_time'])+$v['cycle']*86400+$v['receipt_minute']*60,
                        'settlement_time'=>strtotime(date('Y-m-d').' '.$v['start_time'])+($v['cycle']+$v['start_game_time'])*86400,
                    ];
                    $arrs[]=$arr;
                }



            }
            if($arrs){
                GamblerKingInvestmentUser::insertall($arrs);

            }
            $this->modelMember->setInfo(['id'=>$info['user_id'],'is_king'=>1]);
            //推送交易员动态
            GamblerKingAction::create([
                'king_id'=>$where['id'],
                'cover_id'=>$info->user->cover_id,
                'type'=>4,
                'content'=>'大家好,我是新晋交易员,大家请多多关照！我会努力做到最好！',
            ]);
            //发送系统通知
            user_notice($info->user_id,'恭喜您，通过了交易员的申请，从
            现在这一刻起，您就是我们Ccie的交易员拉，请立即前往游戏中心，创建您的基础数据的统计报表，有助您的委托量哦');
            //发送短信通知
            $lang=in_array($info->user['area'],['86','852','853','886'])?'zh-hk':'en-us';
            $content=getConfig('king_check_success_'.$lang);
            $datas = [
                'mobile' => $info->user['mobile'],
                'content' => $content,
                'create_time' => TIME_NOW,
                'sms_type' => 15,
                'type' => 0,
                'area'=>$info->user['area']
            ];
            $sms=UserSms::create($datas);

            if(getConfig('sms_is_test')!=1){
                $state=send_sms($info->user['mobile'],$content ,config('settings'),$info->user['area']);
                if($state){
                    UserSms::where(['id'=>$sms->id])->update(['state'=>2]);
                }
            }

        }
        if($stat==3){
            //发送系统通知
            user_notice($info->user_id,'很遗憾的通知您，您的申请未能通过，请您核对您的申请信息，或者再次重新提交您的申请，感谢您的支持');

            //发送短信通知
            $lang=in_array($info->user['area'],['86','852','853','886'])?'zh-hk':'en-us';
            $content=getConfig('king_check_fail_'.$lang);
            $datas = [
                'mobile' => $info->user['mobile'],
                'content' => $content,
                'create_time' => TIME_NOW,
                'sms_type' => 16,
                'type' => 0,
                'area'=>$info->user['area']
            ];
            $sms=UserSms::create($datas);

            if(getConfig('sms_is_test')!=1){
                $state=send_sms($info->user['mobile'],$content ,config('settings'),$info->user['area']);
                if($state){
                    UserSms::where(['id'=>$sms->id])->update(['state'=>2]);
                }
            }


        }
        return $result ? [RESULT_SUCCESS, '操作成功'] : [RESULT_ERROR, '操作失败'];
    }


    /**
     * 交易员分类编辑
     */
    public function KingLevelEdit($data = [])
    {

        $validate_result = $this->validateKingLevel->scene('edit')->check($data);

        if (!$validate_result) {

            return [RESULT_ERROR, $this->validateKingLevel->getError()];
        }
        if(!empty($data['parent_id'])){
            $url = url('kingLevelListStrengths');
        }else{
            $url = url('KingLevelList');
        }


        $result = $this->modelKingCategory->setInfo($data);

        $handle_text = empty($data['id']) ? '新增' : '编辑';

        $result && action_log($handle_text, '交易员分类' . $handle_text . '，name：' . $data['name']);

        return $result ? [RESULT_SUCCESS, '操作成功', $url] : [RESULT_ERROR, $this->modelKingCategory->getError()];
    }




    /**
     * 获取分类信息
     */
    public function getKingLevelInfo($where = [], $field = true)
    {

        return $this->modelKingCategory->getInfo($where, $field);
    }

    /**
     * 获取交易员分类列表
     */
    public function getKingLevelList($where = [], $field = true, $order = '', $paginate = 0)
    {

        return $this->modelKingCategory->getList($where, $field, $order, $paginate);
    }

    /**
     * 交易员分类删除
     */
    public function KingLevelDel($where = [])
    {

        $result = $this->modelKingCategory->deleteInfo($where);

        $result && action_log('删除', '交易员分类删除，where：' . http_build_query($where));

        return $result ? [RESULT_SUCCESS, '交易员分类删除成功'] : [RESULT_ERROR, $this->modelKingCategory->getError()];
    }


    /**
     * 获取交易员动态列表
     */
    public function getKingActionList($data = [], $field = 'a.*', $order = '')
    {

        $this->modelGamblerKingAction->alias('a');

        if (!empty($data['date1']) && !empty($data['date2'])) {
            $where['a.create_time'] = ['between', [strtotime($data['date'] . ' 00:00:00'), strtotime($data['date1'] . ' 23:59:59')]];
        }
        if(!empty($data['king_id'])){
            $where['m.king_id']=$data['king_id'];
        }
        if(!empty($data['content'])){
            $where['a.content']=$data['content'];
        }

        if(!empty($data['search_data'])){
            $where['a.content']=['like','%'.$data['search_data'].'%'];
        }
        $where['a.' . DATA_STATUS_NAME] = ['neq', DATA_DELETE];
        $count=$this->modelGamblerKingAction->alias('a')->where($where)->count();
        $list=$this->modelGamblerKingAction->alias('a')->field($field)->where($where)->paginate(50);

        return ['list'=>$list,'count'=>$count];
    }


    /**
     * 交易员动态编辑
     */
    public function KingActionEdit($data = [])
    {

        $url = url('KingActionList');

        // empty($data['id']) && $data['member_id'] = MEMBER_ID;

//      $data['content'] = htmlspecialchars_decode($data['content']);
        preg_match_all('/<img.*?src="(.*?)".*?\/?>/i', $data['content'], $out, PREG_PATTERN_ORDER);      //正则匹配img标签的src属性，返回二维数组
        if (!empty($out[1])) {
            foreach ($out[1] as $v) {
                if(!preg_match('/http/',$v)){
                    $url1 = DMOAIN_URL.$v;
                    $data['content'] = str_replace($v, $url1, $data['content']);   //替换相对路径为绝对路径
                }
            }
        }
        $result = $this->modelGamblerKingAction->setInfo($data);

        $handle_text = empty($data['id']) ? '新增' : '编辑';

        $result && action_log($handle_text, '交易员动态' . $handle_text );

        return $result ? [RESULT_SUCCESS, '操作成功', $url] : [RESULT_ERROR, $this->modelGamblerKingAction->getError()];
    }

    /**
     *  交易员动态删除
     */
    public function KingActionDel($where = [])
    {

        $result = $this->modelGamblerKingAction->deleteInfo($where);

        $result && action_log('删除', '交易员动态删除，where：' . http_build_query($where));

        return $result ? [RESULT_SUCCESS, '交易员动态删除成功'] : [RESULT_ERROR, $this->modelGamblerKingAction->getError()];
    }



    /**
     * 交易员信用等级编辑
     */
    public function kingCreditLevelEdit($data = [])
    {

        $validate_result = $this->validateKingLevel->scene('credit')->check($data);

        if (!$validate_result) {

            return [RESULT_ERROR, $this->validateKingLevel->getError()];
        }


        $url = url('KingCreditLevelList');
        $result = $this->modelKingCreditLevel->setInfo($data);

        $handle_text = empty($data['id']) ? '新增' : '编辑';

        $result && action_log($handle_text, '交易员信用等级' . $handle_text . '，name：' . $data['credit_name']);

        return $result ? [RESULT_SUCCESS, '操作成功', $url] : [RESULT_ERROR, $this->modelKingCategory->getError()];
    }




    /**
     * 获取分类信息
     */
    public function getkingCreditLevelInfo($where = [], $field = true)
    {

        return $this->modelKingCreditLevel->getInfo($where, $field);
    }

    /**
     * 获取交易员分类列表
     */
    public function KingCreditLevelList($where = [], $field = true, $order = '', $paginate = 0)
    {

        return $this->modelKingCreditLevel->getList($where, $field, $order, $paginate);
    }


    /**
     * 获取交易员心语信息
     */
    public function getKingDescribeInfo($where = [], $field = true)
    {

        return $this->modelKingDescribe->getInfo($where, $field);
    }

    /**
     * 获取交易员分类列表
     */
    public function getKingDescribeList($where = [], $field = true, $order = '', $paginate = 0)
    {

        return $this->modelKingDescribe->getList($where, $field, $order, $paginate);
    }



    /**
     * 交易员信用等级编辑
     */
    public function kingDescribeEdit($data = [])
    {
        if($data['type']==1){
            $url = url('KingDescribeList');
        }else{
            $url = url('KingDescribeList1');
        }


        $result = $this->modelKingDescribe->setInfo($data);

        $handle_text = empty($data['id']) ? '新增' : '编辑';

        $result && action_log($handle_text, '交易员心语' . $handle_text . '，标题：' . $data['name']);

        return $result ? [RESULT_SUCCESS, '操作成功', $url] : [RESULT_ERROR, $this->modelKingDescribe->getError()];
    }

    /**
     * 获取交易员订单列表
     */
    public function getKingOrderList($data = [], $field = 'a.*', $order = '')
    {


        if (!empty($data['date1']) && !empty($data['date2'])) {
            $where['a.create_time'] = ['between', [strtotime($data['date1'] . ' 00:00:00'), strtotime($data['date2'] . ' 23:59:59')]];
        }
        if(!empty($data['king_id'])){
            $where['m.king_id']=$data['king_id'];
        }
        if(!empty($data['content'])){
            $where['a.content']=$data['content'];
        }

        if(!empty($data['search_data'])){
            $where['c.name|u.username|a.user_id']=$data['search_data'];
        }
        $where['a.' . DATA_STATUS_NAME] = ['neq', DATA_DELETE];

        $count=$this->modelGamblerKingInvestmentUser->alias('a')->join('__MEMBER__ u' ,'a.user_id = u.id')->join('__GAMBLER_KING__ c' ,'a.king_id = c.id')->where($where)->count();
        $list=$this->modelGamblerKingInvestmentUser->alias('a')->field($field)->join('__MEMBER__ u' ,'a.user_id = u.id')->join('__GAMBLER_KING__ c' ,'a.king_id = c.id')->where($where)->order('state asc,create_time desc')->paginate(DB_LIST_ROWS);

        return ['list'=>$list,'count'=>$count];
    }

    /*
     * 查看委托人
     */
    /**
     * @param array $data
     * @param string $field
     * @param string $order
     * @param \Illuminate\Config\Repository|int|mixed $paginate
     * @return array
     * @throws \think\Exception
     * @throws \think\exception\DbException
     */
    public function getShowUserList($data = [], $field = 'a.*,c.username ', $order = '', $paginate = DB_LIST_ROWS)
    {



        $where = $where1 = [];
        if (!empty($data['date1']) && !empty($data['date2'])) {
            $where['a.create_time'] = ['between', [strtotime($data['date1'] . ' 00:00:00'), strtotime($data['date2'] . ' 23:59:59')]];
        }
        if (!empty($data['search_data'])) {
            $where['a.user_id|c.username|c.mobile'] = $data['search_data'];

        }
        if (!empty($data['investment_type'])) {
            $where['a.investment_type'] = $data['investment_type'];
        }

        $where['a.status'] =1;
        if (!empty($data['king_id'])) {
            $where['a.king_id'] = $data['king_id'];
        }
        if (!empty($data['user_investment_id'])) {
            $where['a.user_investment_id'] = $data['user_investment_id'];
        }

        $list =  $this->modelUserKingInvestment->alias('a')->join('__MEMBER__ c' ,'a.user_id = c.id')->field($field)->where($where)->order($order)->paginate($paginate, false, ['query' => $data]);

        $count =  $this->modelUserKingInvestment->alias('a')->join('__MEMBER__ c' ,'a.user_id = c.id')->field($field)->where($where)->count();
        $money=$this->modelUserKingInvestment->alias('a')->join('__MEMBER__ c' ,'a.user_id = c.id')->field($field)->where($where)->sum('money')+0;

        return ['count'=>$count,'list'=>$list,'money'=>$money];



    }


    /**
     * 交易员订单状态修改
     */

    public function  king_order_update($data){

        if(!empty($data['state'])){
            Db::startTrans();
            try{
            $info=$this->modelUserKingInvestment->where(['id'=>$data['id']])->lock(true)->find();

                if($data['state']==2){

                    if(!$info){
                        return ajaxreturn(1,lang('订单不存在'));
                    }
                    if($info->kinguser->state==3){
                        return ajaxreturn(1,lang('产品已开始,不能解除'));
                    }
                    if($info->kinguser->state==4 ){
                        return ajaxreturn(1,lang('产品已结束,不能解除'));
                    }
                    if($info->kinguser->state==5 ){
                        return ajaxreturn(1,lang('产品已分红,不能解除'));
                    }
                    $total=$info['money'];

                    $info->cancel_order('后台解除');

                    $info->kinguser->surplus_money-=$total;
                    $info->kinguser->total_money-=$total;
                    $info->kinguser->king_win_account-=$info['balance'];
                    $info->kinguser->stop_lose_account-=$info['balance_lock'];
                    $info->kinguser->save();


                }
                $info->state=$data['state'];
                if($data['state'])
                $info->save();
                Db::commit();
                return [RESULT_SUCCESS, '操作成功'];
            }catch (\Exception $e){
                Db::rollback();
                return [RESULT_ERROR,$e->getMessage()];
            }

        }
    }

    /**
     * 交易员产品修改
     */

    public function  king_investment_update($data){
        //停止下注
        if(!empty($data['is_stop_bets'])){
            $this->modelGamblerKingInvestmentUser->setInfo(['id'=>$data['id'],'is_stop_bets'=>1]);
            return [RESULT_SUCCESS, '操作成功'];
        }
        if(!empty($data['state'])){
            Db::startTrans();
            try{
                $info=$this->modelGamblerKingInvestmentUser->where(['id'=>$data['id']])->lock(true)->find();

                if($data['state']==4){

                    //取消委托
                    $user_investment=UserKingInvestment::where(['user_investment_id'=>$info->id,'state'=>0])->select();
                    SbNotice::create([
                        'type'=>5,
                        'user_id'=>$info->user_id,
                        'shop_name'=>$info->investment->data['name'],

                    ]);
                    foreach ($user_investment as $k=>$v){
                      $v->cancel_order('后台取消委托解除');
//                        //等级降级
//                        $v->member->lei_money-=$v['money'];
//                        $v->member->save();
//                        $v->member->downgrade($v['money']);
                        $v->state=3;
                        $v->save();
                    }

                    $info->surplus_money=0;
                    $info->total_money-=0;
                    $info->king_win_account=0;
                    $info->stop_lose_account-=0;

                }
                if($data['state']==5){
                    $info->get_reward();
                }

                if($data['state']==2){
                    SbNotice::create([
                        'type'=>6,
                        'user_id'=>$info->user_id,
                        'shop_name'=>$info->investment->data['name'],
                        'number'=>$info->total_money

                    ]);
                    user_notice($info->user_id,'您的交易员产品'.$info->investment->data['name'].$info->round.'期募集成功！');
                    UserKingInvestment::where(['user_investment_id'=>$info['id'],'state'=>1])->update(['state'=>3]);
                    UserKingInvestment::where(['user_investment_id'=>$info['id'],'state'=>0])->update(['state'=>5]);
                }
                $info->state=$data['state'];
                $info->save();
                if($info->investment->status==1){
                    //重新创建产品
                    $roud=GamblerKingInvestmentUser::where(['investment_id'=>$info->investment_id,   'king_id'=>$info->king_id,])->order('id desc')->value('round');
                    $count=GamblerKingInvestmentUser::where(['investment_id'=>$info->investment_id,   'king_id'=>$info->king_id,'state'=>2])->count();
                    $count1=GamblerKingInvestmentUser::where(['investment_id'=>$info->investment_id,   'king_id'=>$info->king_id,'state'=>3])->count();
                    $days=$count*($info->investment['cycle']+$info->investment['start_game_time'])+$count1*$info->investment['start_game_time'];
                    $minutes=$count*$info->investment['receipt_minute']*60;
                    if($days==0){
                        $days=$info->investment['cycle'];
                    }
                    if($minutes==0){
                        $minutes=$info->investment['receipt_minute']*60;
                    }
                    GamblerKingInvestmentUser::create([
                        'investment_id'=>$info->investment_id,
                        'king_id'=>$info->king_id,
                        'user_id'=>$info->user_id,
                        'state'=>1,
                        'round'=>$roud+1,
                        'price'=>$info->investment->price,
                        'max_money'=>$info->investment->superior_money,
                        // 'start_time'=>$this->investment['start_time_int'],
                        // 'expire_time'=>$this->investment['start_game_int'],
                        // 'start_game_end_int'=>$this->investment['start_game_end_int'],
                        // 'settlement_time'=>$this->investment['end_time_int'],
                        'start_time' => strtotime(date('Y-m-d').' '.$info->investment['start_time']),
                        'expire_time' => strtotime(date('Y-m-d').' '.$info->investment['start_time'])+$days*86400,
                        'start_game_end_int' => strtotime(date('Y-m-d').' '.$info->investment['start_time'])+$days*86400+$minutes,
                    ]);
                }
                Db::commit();
                return [RESULT_SUCCESS, '操作成功'];
            }catch (\Exception $e){
                Db::rollback();
                return [RESULT_ERROR,$e->getMessage()];
            }

        }
    }


    /**
     * 交易员手动分红
     */

    public function  kingbonus($data){
        Db::startTrans();
        try{
            $info=$this->modelGamblerKingInvestmentUser->where(['id'=>$data['id']])->lock(true)->find();
            if($info['state']!=3){
                return [RESULT_ERROR,'订单状态已发生改变'];
            }
            $info->king_reward($data['bonus']);

            Db::commit();
            return [RESULT_SUCCESS, '操作成功'];
        }catch (\Exception $e){
            Db::rollback();
            return [RESULT_ERROR,$e->getMessage()];
        }

    }

}
